/*
 * Copyright 2010 Torokina Networks Pty Ltd
 */

package habi.cat.youdao.supermemo;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Nodes;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

/**
 *
 * @author Jeff Huang (jeff.huang@ca.com)
 */
public class YouDaoWordLoader {

    public List<YouDaoWordItem> load(File file) throws ParsingException, ValidityException, IOException {
        Builder builder = new Builder();
        Document doc = builder.build(file);

        return load(doc);

    }

    public List<YouDaoWordItem> load(Document doc) {
        Nodes wordItems = doc.query("/wordbook/item");
        List<YouDaoWordItem> list = new LinkedList<YouDaoWordItem>();
        
        for(int k=0; k<wordItems.size(); ++k) {
            Element el = (Element)wordItems.get(k);
            Element child = el.getFirstChildElement("word");
            if(child == null && child.getValue() != null)
                continue;
            YouDaoWordItem item = new YouDaoWordItem();
            item.setWord(child.getValue().trim());
            child = el.getFirstChildElement("trans");
            if(child != null && child.getValue() != null) {
                item.setTrans(child.getValue().trim());
            }
            child = el.getFirstChildElement("phonetic");
            if(child != null && child.getValue() != null) {
                item.setPhonetic(child.getValue().trim());
            }
            list.add(item);
        }

        return list;
    }
}
